<?php

class StrMark{
    private static $getInstance;
    private $img_addr;
    private $suffix;
    private $str;
    private $fonts;
    private $img_name;
    private $dir;

    private function __construct($conf){
        $this->init($conf);
        $this->getImgInfo();
    }

    private function __clone(){

    }

    static function getInstance($conf){
        if(!self::$getInstance instanceof self){
            return self::$getInstance = new self($conf);
        }

        return self::$getInstance;
    }

    private function init($conf){
        $this->img_addr = empty($conf['img_addr']) ? '' : $conf['img_addr'];
        $this->str = empty($conf['str']) ? '' : $conf['str'];
        $this->dir = empty($conf['dir']) ? 'strmark/' : $conf['dir'];
        $this->img_name = empty($conf['img_name']) ? '' : $conf['img_name'];
        $this->fonts = empty($conf['fonts']) ? '' : $conf['fonts'];
    }

    private function getImgInfo(){
        list($w, $h, $type) = getimagesize($this->img_addr);

        $type_arr = [1 => 'gif', 2 => 'jpeg', 3 => 'png']; //获得后缀

        $this->suffix = $type_arr[$type];
    }

    function make(){
        $image_cre = 'imagecreatefrom' . $this->suffix; //变量函数

        $pre_img = $image_cre($this->img_addr); //原图

        $red = imagecolorallocate($pre_img, 255, 0, 0); //给图片上颜色

        $x = 50; //  距离左边50
        $y = 50; //  距离上边50

        // 添加文字 参数 图片路径 字体大小 旋转角度 距离左边 距离右边 字体颜色 文字文件 文字
        imagettftext($pre_img, 50, 0, $x, $y, $red, $this->fonts, $this->str);

        // header("Content-Type:image/{$this->suffix}");

        $save = 'image' . $this->suffix;

        $str_mark_dir = $this->dir . '/strmark/'; //保存路径
        if (!is_dir($str_mark_dir)) {
            mkdir($str_mark_dir, 0777, TRUE);
        }

        // 保存文字水印图片
        $save($pre_img, $str_mark_dir . 'strmark' . $this->img_name);

        imagedestroy($pre_img);

        return $str_mark_dir . 'strmark' . $this->img_name;
    }
}